package com.huiquan.analysis.controller;

import com.huiquan.analysis.constants.AnalysisSentenceConstant;
import com.huiquan.analysis.domain.*;
import com.huiquan.analysis.service.AnalysisSentenceService;
import com.huiquan.foundation.constant.TabID;
import com.huiquan.framework.base.ReturnCode;
import com.huiquan.framework.base.ReturnData;
import com.huiquan.framework.utils.RequestParamUtil;
import com.huiquan.framework.utils.ReturnUtil;
import com.huiquan.sphinx.SphinxException;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class AnalysisSentenceController {

    @Autowired
    private AnalysisSentenceService analysisSentenceService;

    /**
     * 进入词语列表画面
     *
     * @param req
     * @param resp
     * @return
     * @throws SphinxException
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/analysis/sentence_list.htm")
    public ModelAndView list(HttpServletRequest req) throws SphinxException {
        String tabid = req.getParameter("tabid");
        String secondType = req.getParameter("secondType");
        // 维护页面参数到session
        int type;
        int labelStatus;
        Map<String, Object> pageParam;
        List<AnalysisSearchParam> searchParams = new ArrayList<>(); // 多词语查询

        if (tabid != null && !tabid.isEmpty()) {
            pageParam = new HashMap<>();
            pageParam.put("tabid", tabid);
            pageParam.put("secondType", secondType);

            type = AnalysisSentenceConstant.TYPE_ZS;
            if (TabID.isAnalysisZs(tabid)) {
                type = AnalysisSentenceConstant.TYPE_ZS;
            } else if (TabID.isAnalysisXbs(tabid)) {
                type = AnalysisSentenceConstant.TYPE_XBS;
            } else if (TabID.isAnalysisCt(tabid)) {
                type = AnalysisSentenceConstant.TYPE_CT;
            }
            pageParam.put("type", String.valueOf(type));

            labelStatus = TabID.getAnalysisLabelStatus(tabid);
            pageParam.put("labelStatus", String.valueOf(labelStatus));

            req.getSession().setAttribute("pageParam", pageParam);
        } else {
            pageParam = (Map<String, Object>) req.getSession().getAttribute("pageParam");
            type = Integer.parseInt(pageParam.get("type").toString());
            labelStatus = Integer.parseInt(pageParam.get("labelStatus").toString());
            if (type == AnalysisSentenceConstant.TYPE_XBS) {
                secondType = pageParam.get("secondType").toString();
            }
            Map<String, Object> map = req.getParameterMap();
            String[] vocabularyKeys = (String[]) map.get("vocabularyKey");
            if (vocabularyKeys != null && vocabularyKeys.length > 0) {
                String[] propertyKeys = (String[]) map.get("propertyKey");
                String[] position1Keys = (String[]) map.get("position1Key");
                String[] position2Keys = (String[]) map.get("position2Key");
                String[] oppositePropertyFlagKeys = (String[]) map.get("oppositePropertyFlagKey");
                String[] oppositePosition1FlagKeys = (String[]) map.get("oppositePosition1FlagKey");
                for (int i = 0; i < vocabularyKeys.length; i++) {
                    if (!vocabularyKeys[i].trim().isEmpty()) {
                        AnalysisSearchParam searchParam = new AnalysisSearchParam();
                        searchParam.setId((long) i);
                        searchParam.setVocabulary(vocabularyKeys[i].trim());
                        searchParam.setProperty(propertyKeys[i] == null ? null : propertyKeys[i].trim());
                        searchParam.setPosition1(position1Keys[i] == null ? null : position1Keys[i].trim());
                        searchParam.setPosition2(position2Keys[i] == null ? null : position2Keys[i].trim());
                        searchParam.setOppositePropertyFlag(oppositePropertyFlagKeys[i]);
                        searchParam.setOppositePosition1Flag(oppositePosition1FlagKeys[i]);
                        searchParams.add(searchParam);
                    }
                }
                pageParam.put("searchParams", searchParams);
            }
        }

        // 获取页面参数，如果request中有值则修改session，否则从session中拿值
        String start = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "start");

        if (searchParams.isEmpty()) {
            searchParams = (List<AnalysisSearchParam>) pageParam.get("searchParams");
        }

        return analysisSentenceService.list(start, type, labelStatus, searchParams, secondType);
    }

    /**
     * 进入词语编辑画面
     *
     * @param req
     * @param resp
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/analysis/sentence_pre_edit.htm")
    public ModelAndView preEdit(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String idStr = req.getParameter("id");

        @SuppressWarnings("unchecked")
        Map<String, Object> pageParam = (Map<String, Object>) req.getSession().getAttribute("pageParam");
        int type = Integer.parseInt(RequestParamUtil.getParamByRequestOrSession(req, pageParam, "type"));

        Object secondTypeObject = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "secondType");
        String secondType = "";
        if (secondTypeObject != null) {
            secondType = secondTypeObject.toString();
        }
        return analysisSentenceService.preEdit(idStr, type, secondType);
    }

    /**
     * 进行词语编辑操作
     *
     * @param req
     * @param resp
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/analysis/sentence_edit.do")
    public ReturnData edit(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        User user = (User) req.getSession().getAttribute("user");
        String idStr = req.getParameter("id");
        Map<String, Object> map = req.getParameterMap();
        String[] vocabularyStrs = (String[]) map.get("vocabulary");
        String[] characterStrs = (String[]) map.get("character");
        String[] propertyStrs = (String[]) map.get("property");
        String[] position1Strs = (String[]) map.get("position1");
        String[] position2Strs = (String[]) map.get("position2");
        String[] sourceStrs = (String[]) map.get("source");

        String type = RequestParamUtil.getParamBySession(req, "type");
        String secondType = RequestParamUtil.getParamBySession(req, "secondType");
        ReturnData result = analysisSentenceService.edit(type, secondType, idStr, user, vocabularyStrs, characterStrs,
                propertyStrs, position1Strs, position2Strs, req, sourceStrs);
        analysisSentenceService.asynchronousUpdateSphinxIndex("vocabulary" + type + "_delta");
        // 如果是从句子分类中进来的话重定向到句子分类的界面
        String tabid = (String) req.getSession().getAttribute("tabid");
        Map<String, Object> pageParam = (Map<String, Object>) req.getSession().getAttribute("pageParam");

        if ("0".equals(result.getReturnCode().getCode()) && (StringUtils.equals("1", (String) pageParam.get("markSentenceFlag")) || StringUtils.equals("2", (String) pageParam.get("markSentenceFlag")))) {
            if (StringUtils.equals("1", (String) pageParam.get("markSentenceFlag"))) {
                return ReturnUtil.fail(ReturnCode.REDIRECT_UNLABEL_MARK_SENTENCE);
            } else {
                return ReturnUtil.fail(ReturnCode.REDIRECT_LABEL_MARK_SENTENCE);
            }
        }
        return result;
    }

    /**
     * 进行词语编辑操作
     *
     * @param req
     * @param resp
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/analysis/sentence_subdivision_edit.do")
    public ReturnData subdivisionEdit(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        User user = (User) req.getSession().getAttribute("user");
        String idStr = req.getParameter("id");
        Map<String, Object> map = req.getParameterMap();
        String[] vocabularyStrs = (String[]) map.get("vocabulary");
        String[] characterStrs = (String[]) map.get("character");
        String[] propertyStrs = (String[]) map.get("property");
        String[] position1Strs = (String[]) map.get("position1");
        String[] position2Strs = (String[]) map.get("position2");

        String type = RequestParamUtil.getParamBySession(req, "type");
        String secondType = RequestParamUtil.getParamBySession(req, "secondType");
        ReturnData result = analysisSentenceService.subdivisionEdit(type, secondType, idStr, user, vocabularyStrs, characterStrs,
                propertyStrs, position1Strs, position2Strs, req);
        analysisSentenceService.asynchronousUpdateSphinxIndex("vocabulary" + type + "_delta");
        return result;
    }


    /**
     * 删除句子
     *
     * @param req
     * @param resp
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/analysis/sentence_delete.do")
    public ReturnData delete(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        User user = (User) req.getSession().getAttribute("user");
        String idStr = req.getParameter("id");
        Map<String, Object> pageParam = (Map<String, Object>) req.getSession().getAttribute("pageParam");

        String type = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "type");
        String secondType = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "secondType");
        ReturnData result = analysisSentenceService.delete(type, secondType, idStr);
        return result;
    }

    /**
     * 无法标注句子
     *
     * @param req
     * @param resp
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/analysis/sentence_cannottag.do")
    public ReturnData canNotTag(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        User user = (User) req.getSession().getAttribute("user");
        String idStr = req.getParameter("id");
        Map<String, Object> pageParam = (Map<String, Object>) req.getSession().getAttribute("pageParam");

        String type = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "type");
        String secondType = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "secondType");
        ReturnData result = analysisSentenceService.canNotTag(type, secondType, idStr);
        return result;
    }

    /**
     * 可以标注句子
     *
     * @param req
     * @param resp
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/analysis/sentence_cantag.do")
    public ReturnData canTag(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        User user = (User) req.getSession().getAttribute("user");
        String idStr = req.getParameter("id");
        Map<String, Object> pageParam = (Map<String, Object>) req.getSession().getAttribute("pageParam");

        String type = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "type");
        String secondType = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "secondType");
        ReturnData result = analysisSentenceService.canTag(type, secondType, idStr);
        return result;
    }

    /**
     * 删除句子
     *
     * @param req
     * @param resp
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/analysis/sentence_recover.do")
    public ReturnData recoverAnalysis(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        User user = (User) req.getSession().getAttribute("user");
        String idStr = req.getParameter("id");
        Map<String, Object> pageParam = (Map<String, Object>) req.getSession().getAttribute("pageParam");

        String type = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "type");
        String secondType = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "secondType");
        ReturnData result = analysisSentenceService.recoverAnalysis(type, secondType, idStr);
        analysisSentenceService.asynchronousUpdateSphinxIndex("vocabulary" + type + "_delta");
        return result;
    }

    /**
     * 强制进行词语编辑操作
     *
     * @param req
     * @param resp
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/analysis/sentence_force_edit.do")
    public ReturnData forceEdit(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        User user = (User) req.getSession().getAttribute("user");
        Map<String, Object> map = (Map<String, Object>) req.getSession().getAttribute("objMap");
        boolean mergeFlag = (boolean) map.get("mergeFlag");
        Map<String, Object> searchParam = (Map<String, Object>) map.get("searchParam");
        String newStr = (String) map.get("newStr");
        AnalysisDictionary dic = (AnalysisDictionary) map.get("dic");
        List<AnalysisVocabulary> vocabularys = (List<AnalysisVocabulary>) map.get("vocabularys");
        AnalysisSentence sentence = (AnalysisSentence) map.get("sentence");
        req.getSession().removeAttribute("objMap");
        String secondType = RequestParamUtil.getParamBySession(req, "secondType");
        ReturnData result = analysisSentenceService.forceEditAndUpdateDictionary(mergeFlag, searchParam, newStr, dic,
                vocabularys, sentence, user, secondType);
        int type = Integer.valueOf(searchParam.get("type").toString());
        analysisSentenceService.asynchronousUpdateSphinxIndex("vocabulary" + type + "_delta");
        return result;
    }

    @ResponseBody
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/analysis/preview.do")
    public ReturnData preview(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        Map<String, Object> map = req.getParameterMap();
        String[] vocabularyStrs = (String[]) map.get("vocabulary");
        String[] characterStrs = (String[]) map.get("character");
        String[] propertyStrs = (String[]) map.get("property");
        String idStr = req.getParameter("id");

        return analysisSentenceService.preview(idStr, vocabularyStrs, characterStrs, propertyStrs);
    }


    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/analysis/sentence_del_list.htm")
    public ModelAndView deleteList(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String tabid = req.getParameter("tabid");
        String secondType = "";
        // 维护页面参数到session
        int type;
        Map<String, Object> pageParam;
        if (tabid != null && !tabid.isEmpty()) {
            pageParam = new HashMap<>();
            pageParam.put("tabid", tabid);
            pageParam.put("secondType", secondType);
            pageParam.put("exactSearchFlag", "0");

            type = AnalysisSentenceConstant.TYPE_ZS;
            if (TabID.isAnalysisZs(tabid)) {
                type = AnalysisSentenceConstant.TYPE_ZS;
            } else if (TabID.isAnalysisXbs(tabid)) {
                type = AnalysisSentenceConstant.TYPE_XBS;
            } else if (TabID.isAnalysisCt(tabid)) {
                type = AnalysisSentenceConstant.TYPE_CT;
            }
            pageParam.put("type", String.valueOf(type));

            req.getSession().setAttribute("pageParam", pageParam);
        } else {
            pageParam = (Map<String, Object>) req.getSession().getAttribute("pageParam");
            type = Integer.parseInt(pageParam.get("type").toString());
        }

        // 获取页面参数，如果request中有值则修改session，否则从session中拿值
        String start = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "start");
        String sentence = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "sentence");
        String exactSearchFlag = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "exactSearchFlag");
        String countPerPageStr = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "countPerPage");
        secondType = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "secondType");

        return analysisSentenceService.deleteList(start, sentence, type, exactSearchFlag, countPerPageStr, secondType);
    }

    /**
     * 进入无法标注页面
     *
     * @param req
     * @param resp
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/analysis/sentence_cannottag_list.htm")
    public ModelAndView canNotTagList(HttpServletRequest req, HttpServletResponse resp) throws SphinxException {
        String tabid = req.getParameter("tabid");
        String secondType = req.getParameter("secondType");
        // 维护页面参数到session
        int type;
        Map<String, Object> pageParam;

        if (tabid != null && !tabid.isEmpty()) {
            pageParam = new HashMap<>();
            pageParam.put("tabid", tabid);
            pageParam.put("secondType", secondType);
            pageParam.put("exactSearchFlag", "0");
            type = AnalysisSentenceConstant.TYPE_XBS;
            pageParam.put("type", String.valueOf(type));
            req.getSession().setAttribute("pageParam", pageParam);
        } else {
            pageParam = (Map<String, Object>) req.getSession().getAttribute("pageParam");
            type = Integer.parseInt(pageParam.get("type").toString());
            if (type == AnalysisSentenceConstant.TYPE_XBS) {
                secondType = pageParam.get("secondType").toString();
            }
        }

        // 获取页面参数，如果request中有值则修改session，否则从session中拿值
        String start = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "start");
        String sentence = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "sentence");
        String exactSearchFlag = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "exactSearchFlag");
        String countPerPageStr = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "countPerPage");
        secondType = RequestParamUtil.getParamByRequestOrSession(req, pageParam, "secondType");

        return analysisSentenceService.canNotTagList(start, sentence, type, exactSearchFlag, countPerPageStr, secondType);
    }


    /**
     * 词语预览
     *
     * @param req
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/analysis/analysis_preview.do")
    public ReturnData analysisPreview(HttpServletRequest req) {
        String idStr = req.getParameter("id");
        Map<String, Object> map = req.getParameterMap();
        String[] vocabularyStrs = (String[]) map.get("vocabulary");
        String[] characterStrs = (String[]) map.get("character");
        String[] propertyStrs = (String[]) map.get("property");
        String[] position1Strs = (String[]) map.get("position1");
        String[] position2Strs = (String[]) map.get("position2");
        String[] isPronouns = (String[]) map.get("isPronoun");
        User user = (User) req.getSession().getAttribute("user");

        String type = RequestParamUtil.getParamBySession(req, "type");
        String secondType = RequestParamUtil.getParamBySession(req,"secondType");
        ReturnData result = analysisSentenceService.analysisPreview(idStr, vocabularyStrs,
                characterStrs, propertyStrs, position1Strs, position2Strs, Integer.parseInt(type),isPronouns,secondType,user,map);

        return result;
    }


    /**
     * 改变有效性flag
     * @param req
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/analysis/change_valid_flag.do")
    public ReturnData changeValid(HttpServletRequest req) {
        String idStr = req.getParameter("id");
        String check = req.getParameter("check");

        User user = (User) req.getSession().getAttribute("user");

        ReturnData result = analysisSentenceService.changeValid(idStr,user,check);

        return result;
    }
    /**
     * 词语预览
     *
     * @param req
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    @ResponseBody
    @RequestMapping(value = "/analysis/subdivision_preview.do")
    public ReturnData subdivisionPreview(HttpServletRequest req) {
        String idStr = req.getParameter("id");
        Map<String, Object> map = req.getParameterMap();
        String[] vocabularyStrs = (String[]) map.get("vocabulary");
        String[] characterStrs = (String[]) map.get("character");
        String[] propertyStrs = (String[]) map.get("property");
        String[] position1Strs = (String[]) map.get("position1");
        String[] position2Strs = (String[]) map.get("position2");
        String[] isPronouns = (String[]) map.get("isPronoun");
        User user = (User) req.getSession().getAttribute("user");

        String type = RequestParamUtil.getParamBySession(req, "type");
        String secondType = RequestParamUtil.getParamBySession(req,"secondType");
        ReturnData result = analysisSentenceService.subdivPreview(idStr, vocabularyStrs,
                characterStrs, propertyStrs, position1Strs, position2Strs, Integer.parseInt(type),isPronouns,secondType,user,map,req);

        return result;
    }
}
